package com.zjw.zy.heart.wbsocket;

import com.zjw.zy.heart.smi.JustWithIt;
import com.zjw.zy.heart.utils.LogUtils;
import com.zjw.zy.heart.wbsocket.socket.WsMessage;
import com.zjw.zy.pal.WsMessageWrap;
import jakarta.websocket.Session;

import java.io.IOException;
import java.nio.ByteBuffer;

public class WsSender {

    private static final String TAG = "WsSender";

    public static boolean sendToClient(Session session, WsMessage message) {
        if (session != null && session.isOpen()) {
            try {
                if (WsStreamProcessor.sendByStream(message, obj -> {
                    try {
                        session.getBasicRemote().sendBinary(ByteBuffer.wrap(obj));
                    } catch (IOException e) {
                        LogUtils.e(TAG, e.getMessage());
                    }
                })) {
                    return true;
                }
                session.getBasicRemote().sendText(message.toJson());
                return true;
            } catch (IOException e) {
                LogUtils.e(TAG, "sendToClient", e);
                return false;
            }
        }
        return false;
    }

    public static boolean convertAndSendToClient(Session session, WsMessage message) {
        message.jsonPayload();
        return sendToClient(session, message);
    }

    public static void close(Session session) {
        if (session != null && session.isOpen()) {
            try {
                session.close();
            } catch (IOException e) {
                LogUtils.e(TAG, "sendToClient", e);
            }
        }
    }
}
